package com.hddznet.uniplatform.sm.config.cas;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	
	public CasAuthenticationFilter(String defaultFilterProcessesUrl) {
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl, "GET"));
    }

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		
		CasAuthenticationToken authenticationToken =  null;
	    String code = request.getParameter("code");
	    String state = request.getParameter("state");
	    log.info("CasAuthenticationFilter: Code={}, State={}", code, state);
	    
	    if (code != null) {
	    	authenticationToken = new CasAuthenticationToken(code);
	    }
	    setDetails(request, authenticationToken);
        // 返回验证结果
	    Authentication auth =  this.getAuthenticationManager().authenticate(authenticationToken);
	    return auth;
	}
	
	private void setDetails(HttpServletRequest request, CasAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

}
